package com.didispace.boot.test;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;


public class Main {

    /**
     * load spring.factories test
     * 
     * @param args
     */
    public static void main(String[] args) {
        loadResource(Main.class.getClassLoader(), "META-INF/spring.factories");
        System.out.println("=====");
        // loadResource(Main.class.getClassLoader(),
        // "META-INF/spring.provides");
        // ConfigurationClassParser 对配置的 "META-INF/spring.factories" 进行解析
        // 1、对注解解析 ，2、对该类内部类 进行解析

        // ImportBeanDefinitionRegistrar registrar =
        // BeanUtils.instantiateClass(MybatisAutoConfiguration.class,
        // ImportBeanDefinitionRegistrar.class);
        // System.out.println(registrar);

        // web 配置类 WebMvcAutoConfiguration
    }


    public static List loadResource(ClassLoader classLoader, String name) {
        try {
            Enumeration<URL> urls =
                    (classLoader != null ? classLoader.getResources(name) : ClassLoader
                        .getSystemResources(name));
            List<String> result = new ArrayList<String>();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                System.out.println(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                System.out.println(properties);
                // String factoryClassNames =
                // properties.getProperty(factoryClassName);
                // result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
            }
            return result;
        }
        catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load [" + name + "] factories from location ["
                    + name + "]", ex);
        }
    }

}
